<template>
  <div class="table-default theweekCreate">
    <el-button class="backBtn" type="primary" @click="goback">返回</el-button>
    <el-button type="warning" @click="choseHandler" class="choseBtn">选择生产工单 </el-button>
    <el-button type="success" @click="addSupplier(ruleFormRef)">保存</el-button>

    <!-- <h2 style="padding: 20px 7px">供货商送货单-新增</h2> -->
    <div class="info" style="color: #999; padding: 0px 7px 20px 7px">
      <el-icon style="margin-right: 5px"><InfoFilled /></el-icon>
      <span>请先选择生产工单</span>
    </div>

    <el-form :model="remarkForm" label-width="100px" ref="form">
      <!-- <el-form-item label="备注" prop="remarks">
        <div class="formItem">
          <div style="width: 30%">
            <el-input v-model="remarkForm.remarks" name="remarks" clearable />
          </div>

          <div class="batchIpt" v-if="tableForm.tableData.length != 0">
            <el-input v-model="batchNumber" placeholder="批量输入箱数" clearable />
            <el-date-picker v-model="batchdeliverydate" type="date" placeholder="批量输入日期" style="margin-left: 20px" clearable />
          </div>
        </div>
      </el-form-item> -->
      <!-- {{ batchForm }} -->
      <div class="match-view">
        <el-form :model="batchForm" :inline="true">
          <el-form-item label="计划配置：">
            <el-select v-model="batchForm.plantype" placeholder="批量选择计划配置类型" clearable>
              <el-option v-for="item in plantypeArr" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="计划生产日期：">
            <el-date-picker v-model="batchForm.fplannedstarttime" type="date" value-format="YYYY-MM-DD" placeholder="批量选择计划生产日期" />
          </el-form-item>
          <el-form-item label="计划生产数量：">
            <el-input-number v-model="batchForm.planqty" :min="1" placeholder="批量填写生产数量" />
          </el-form-item>
          <el-form-item label="计划人工数量：">
            <el-input-number v-model="batchForm.plan_labor" :min="1" placeholder="批量填写人工" />
          </el-form-item>
          <el-form-item label="计划生产时长：">
            <el-input-number v-model="batchForm.production_time" :min="1" placeholder="批量填写生产时长" />
          </el-form-item>
          <el-form-item label="备注: ">
            <el-input v-model="batchForm.remark" placeholder="批量填写备注" />
          </el-form-item>
        </el-form>
      </div>

      <el-form-item prop="detailscheck_all">
        <el-dialog v-model="dialogTableVisible" title="选择生产工单" width="95%" style="height: 90vh" destroy-on-close>
          <!-- <openPurchase @send-data="getData" :checkList="checkList" @send-query="getquery"></openPurchase> -->
          <PurchaseOrderVue @send-data="getData"></PurchaseOrderVue>
        </el-dialog>
      </el-form-item>

      <!-- <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick"> -->
      <!-- <el-tab-pane label="本周生产计划" name="purchase"> -->
      <el-form :model="tableForm" label-width="100px" :rules="rules" ref="ruleFormRef">
        <el-table :data="tableForm.tableData" border class="theweektable" show-summary :summary-method="getSummaries">
          <el-table-column label="生产用料清单" prop="fbillno" width="150" />
          <el-table-column label="产品SKU" prop="fmaterialid" width="100" />
          <el-table-column label="产品名称" prop="fmaterialname" width="130" />
          <el-table-column label="生产车间" prop="fworkshopid_name" width="120" />
          <el-table-column label="生产线" prop="fline" width="120" />
          <el-table-column label="计划配置" prop="plantype" width="150">
            <template #default="scope">
              <el-form-item :prop="'tableData.' + scope.$index + '.plantype'" :rules="rules.plantype">
                <el-select v-model="scope.row.plantype" placeholder="选择计划配置类型">
                  <el-option v-for="item in plantypeArr" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="计划生产日期" prop="fplannedstarttime" width="250">
            <template #default="scope">
              <el-form-item :prop="'tableData.' + scope.$index + '.fplannedstarttime'" :rules="rules.fplannedstarttime">
                <el-date-picker v-model="scope.row.fplannedstarttime" value-format="YYYY-MM-DD"  type="date" placeholder="选择计划生产日期" />
                <!-- <el-date-picker v-model="value1" type="date" placeholder="Pick a day" :size="size" /> -->
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="计划生产数量" prop="planqty" width="200">
            <template #default="scope">
              <el-form-item :prop="'tableData.' + scope.$index + '.planqty'" :rules="rules.planqty">
                <el-input-number v-model="scope.row.planqty" :min="1" placeholder="生产数量" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="计划人工" prop="plan_labor" width="200">
            <template #default="scope">
              <el-form-item :prop="'tableData.' + scope.$index + '.plan_labor'" :rules="rules.plan_labor">
                <el-input-number v-model="scope.row.plan_labor" :min="1" placeholder="人工" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="计划生产时长" prop="production_time" width="200">
            <template #default="scope">
              <el-input-number v-model="scope.row.production_time" :min="1" placeholder="生产时长" />
            </template>
          </el-table-column>
          <el-table-column label="计划总工时" prop="plan_total" width="100">
            <template #default="scope">
              <el-form-item :prop="'tableData.' + scope.$index + '.plan_total'">
                {{ isNaN(scope.row.production_time) || isNaN(scope.row.plan_labor) ? 0 : scope.row.production_time * scope.row.plan_labor }}
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="200">
            <template #default="scope">
              <el-form-item :prop="'tableData.' + scope.$index + '.remark'">
                <el-input v-model="scope.row.remark" placeholder="填写备注" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <Destroy @click="destroy(api, scope.row.id)" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <!-- </el-tab-pane> -->
      <!-- </el-tabs> -->
    </el-form>
  </div>
</template>



<script lang="ts" setup>
import { ref, reactive, onUpdated, watch, watchEffect } from 'vue'
import { useCreate } from '/admin/composables/curd/useCreate'
import { useShow } from '/admin/composables/curd/useShow'
import { onMounted } from 'vue'
import PurchaseOrderVue from './openPurchase.vue'
import http from '/admin/support/http'
import { useRouter, useRoute } from 'vue-router'
import categoryTable from './categoryTable.vue'
import { ElMessage } from 'element-plus'
import storage from '/admin/utils/storage'
import { InfoFilled } from '@element-plus/icons-vue'
import { delDetailRouter } from '/admin/utils/delDetailRouter'

const router = useRouter()
const route = useRoute()
let batchForm = reactive({
  plantype: null,
  fplannedstarttime: null,
  planqty: null,
  plan_labor: null,
  production_time: null,
  remark: null,
})

// const props = defineProps({
//   api: String,
//   supplierId: Number,
//   title: String,
//   tableData: Object,
// })

// const tableData = ref([])
const supplierId = ref()
const newSupplierId = ref()
// const categoryShow = ref(false)

const remarkForm = reactive({
  remarks: '',
})

// supplierId.value = props.supplierId || newSupplierId.value

let tableForm = reactive({
  tableData: [],
})

// if (props.tableData) {
//   remarkForm.remarks = props.tableData.remarks
//   tableForm.tableData = props.tableData.detailscheck_all
// } else {
// remarkForm.remarks = ''
// tableForm.tableData = []
// }

// console.log('明细表格数据：', tableForm.tableData)

// const { formData, form, loading, submitForm, close } = useCreate(props.api, props.primary)
// console.log(formData)

const activeName = ref('purchase')

// if (props.primary) {
//   useShow(props.api, props.primary, formData)
// }

const dialogTableVisible = ref(false)

// let Data = reactive({
//   arr: [],
// })

let allArr = reactive([])
let finished = ref(true)

// const tableData = ref([])

const ruleFormRef = ref()

const rules = reactive({
  fplannedstarttime: [{ required: true, trigger: 'change', message: '不能为空' }],
  plantype: [{ required: true, message: '不能为空', trigger: 'change' }],
  planqty: [{ required: true, message: '不能为空', trigger: 'blur' }],
  plan_labor: [{ required: true, message: '不能为空', trigger: 'blur' }],
  production_time: [{ required: true, message: '不能为空', trigger: 'blur' }],
})
let choseData = ref([])

let getData = data => {
  dialogTableVisible.value = false
  console.log('父组件接受的工单数据', data)
  choseData.value = data

  choseData.value.forEach(item => {
    if (tableForm.tableData.length == 0) {
      tableForm.tableData.push(item)
    }
    if (tableForm.tableData.length != 0 && tableForm.tableData.every(ele => ele.id != item.id)) {
      console.log(item.id)
      tableForm.tableData.push(item)
    }
  })

  // // 重新选择
  // console.log(tableForm.tableData)
}

let haveID = ref('')
let FormObj = ref([])

// 添加送货单，获取新ID，生成新品名
const addSupplier = async formEl => {
  if (tableForm.tableData.length == 0) {
    ElMessage.warning('请先选择采购订单！')
  } else {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        console.log('点击添加', tableForm.tableData)

        for (let i = 0; i < tableForm.tableData.length; i++) {
          let obj = {}
          obj.plantype = tableForm.tableData[i].plantype
          obj.fplannedstarttime = tableForm.tableData[i].fplannedstarttime
          obj.planqty = tableForm.tableData[i].planqty
          obj.plan_labor = tableForm.tableData[i].plan_labor
          obj.production_time = tableForm.tableData[i].production_time
          obj.plan_total = tableForm.tableData[i].production_time * tableForm.tableData[i].plan_labor
          obj.remark = tableForm.tableData[i].remark
          obj.production_order_id = tableForm.tableData[i].id
          FormObj.value.push(obj)
        }
        console.log('所需新增提交数据FormObj：', FormObj.value)

        // 新增请求，获取送货单id
        http.post('/pmcsignage/theweekplan', FormObj.value).then(r => {
          console.log('新增请求返回数据：', r.data)
          haveID.value = r.data.data
          ElMessage({
            message: r.data.message,
            type: 'success',
          })

          // 新增成功，切换到详情页
          let routeList = JSON.parse(sessionStorage.getItem('routeList') || '[]')
          routeList = routeList.filter(item => item.title != '本周生产计划新增')
          sessionStorage.setItem('routeList', JSON.stringify(routeList))
          router.push(`/pmcsignage/theweekplan`)
        })
      } else {
        ElMessage({
          message: '有未输入文本！',
          type: 'warning',
        })
      }
    })
  }
}

const editForm = ref({})

// 删除
const delHandler = item => {
  console.log(item)
  tableForm.tableData = tableForm.tableData.filter(ele => ele.id != item.id)
  // tableForm.tableData.splice(index, 1)
  ElMessage.info('删除后不要忘记提交修改哦!')
  // finished.value = true
}

// let emit = defineEmits(['send-data'])

let queryForm = reactive({})

let checkList = ref([])

// let data = ref({
//   fbillno: '',
//   fsupplierid_name: '',
//   state: 0,
// })

let choseHandler = () => {
  dialogTableVisible.value = true
}

// let getquery = data => {
//   queryForm = data
//   console.log('父组件接收的查询数据：', queryForm)
//   // getPurchase(queryForm)
// }

const goback = () => {
  delDetailRouter('本周生产计划新增', '/pmcsignage/theweekplan')
}

let plantypeArr = ref([])
let plantypeObj = reactive({})

const getplantype = () => {
  // 类型配置
  http.get('/pmcsignage/plantype').then(r => {
    console.log('类型配置', r.data)
    if (r.data.code == 10000) {
      plantypeArr.value = r.data.data
      plantypeObj = r.data.data.reduce((prev, item) => {
        prev[item.value] = item.label
        return prev
      }, {})
      console.log(plantypeArr.value, plantypeObj)
    } else {
      ElMessage.error(r.data.message)
    }
  })
}

const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '总行数 : ' + tableForm.tableData.length
      return
    }
  })

  return sums
}

watch(batchForm, (newVal, oldVal) => {
  // console.log('监听 batchForm', batchForm)
  tableForm.tableData = tableForm.tableData.map(item => {
    return {
      ...item,
      plantype: newVal.plantype,
      fplannedstarttime: newVal.fplannedstarttime,
      planqty: newVal.planqty,
      plan_labor: newVal.plan_labor,
      production_time: newVal.production_time,
      remark: newVal.remark,
    }
  })
})

onMounted(() => {
  getplantype()
})
onUpdated(() => {
  // console.log(allArr)
  // console.log(formData.value)
})
</script>

<style lang="css">
.batchIpt {
  margin-left: 30px;
  display: flex;
}
.info {
  color: #999;
  padding: 0px 7px 20px 7px;
  display: flex;
  align-items: center;
}
.btnRow {
  margin: 20px;
}
h2 {
  /* margin-left: 10px; */
  text-align: left;
  font-weight: bold;
}
/* .creatClass {
  padding: 0 60px 20px 0;
} */
.formItem {
  width: 100%;
  align-items: center;
  /* background-color: pink; */
  display: flex;
  flex-shrink: 0;
  /* justify-content: space-between; */
  /* justify-content: space-between; */
}

.choseBtn {
  margin: 0 10px;
}
.required {
  transform: translateY(-100px);
  color: red;
}
.demo-tabs {
  margin: 20px 0px 20px 20px;
}
.backBtn {
  margin: 20px 10px;
}
.el-form-item__content {
  margin-left: 0 !important;
}

.el-overlay-dialog {
  top: -70px !important;
}
.el-dialog__body {
  padding: 0 20px 10px;
}
.theweekCreate .el-table .el-table__cell {
  padding: 3px;
}
.theweektable .el-form-item {
  margin: 5px 0 !important;
}
</style>
